<?php
/**
 * Created by PhpStorm.
 * User: zeopean
 * Date: 2015/9/15
 * Time: 17:04
 */
namespace App\Http\Controllers\Api;

use App\Exceptions\AdminException;
use App\Exceptions\SecurityException;
use App\Exceptions\SignInException;
use App\Exceptions\SignUpException;
use App\Http\Requests;
use App\InvestLog;
use App\Investor;
use App\InvestOrg;
use App\Project;
use App\ProjectMilestone;
use App\ProjectUrl;
use App\Services\Tools;
use App\User;
use App\UserInfo;
use App\UserTeams;
use Illuminate\Auth\Guard;
use Illuminate\Support\Facades\Input;
use Auth;
use App\Http\Requests\ChangeUserInfoRequest;
use App\Http\Requests\ProjectRequest;
use App\Exceptions\ProjectException;
use Illuminate\Support\Facades\Session;
use Carbon\Carbon;

class AdminController extends ApiController{

    /**
     * 后台登录操作
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function SignIn(){
        $username = Input::get('username');
        $password = Input::get('password');
        $remember = Input::get('remember');

        if(!$username || !$password)
            return $this->buildResponse(trans('您的用户名或者密码不能为空！'),[],null,'error');

       if(!User::whereUsername($username)->exists())
           return $this->buildResponse(trans('用户名不存在！'),[],null,'error');

       if(!User::whereUsername($username)->whereIsPower(3)->exists())
           return $this->buildResponse(trans('非管理员用户不能登录！'),[],null,'error');


        if(Auth::attempt(['username' => $username , 'password' => $password] , $remember)){
            return $this->buildResponse(trans('欢迎你，管理员！') , Auth::user()) ;
        }

        return $this->buildResponse(trans('您的用户名或者密码不正确!'),[],null,'error');

    }

    /**
     * 管理员添加 创业者信息
     * @param Guard $guard
     * @param ChangeUserInfoRequest $request
     * @param int $id
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function editUserInfoByAdmin(Guard $guard , ChangeUserInfoRequest $request , $role=0)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);
        $id = $request->get('user_id');

        if($id == 0){
            $userInfo = new UserInfo();
            $user_max_id    = User::withTrashed()->orderBy('id' ,'desc')->limit(1)->pluck('id');
            $user_max_id    += 1;
            $virtual_user   = 'pgzhe_user'.$user_max_id;
            $user = new User();
            $user->id       = $user_max_id;
            $user->username = $virtual_user ;
            $user->password = '';
            $user->reg_ip   = '';
            $user->role     = $role;
            $user->save();
        }else{
            $userInfo = UserInfo::whereUserId($id)->first();
        }

        $realname   =   $request -> get('realname');        //用户名
        $user_id    =   $id;                                //用户ID
        $province   =   $request->get('province');          //省份
        $city       =   $request->get('city');              //城市
        $town       =   $request->get('town');              //区 县
        $wechat     =   $request -> get('wechat');          //微信
        $weibo      =   $request -> get('weibo');           //微博
        $maimai     =   $request -> get('maimai');          //脉脉
        $edu_school =   $request -> get('edu_school');      //毕业学校
        $position   =   $request -> get('position');        //职位
        $user_desc  =   $request -> get('user_desc');       //个人介绍

        if(!is_null($realname))$userInfo->realname = $realname;
        if(!is_null($user_id))$userInfo->user_id = $user_id;
        if(isset($user_max_id)) $userInfo->user_id = $user_max_id;
        if(!empty($province)) $userInfo->province = $province;
        if(!empty($city)) $userInfo->city = $city;
        if(!is_null($town))$userInfo->town = $town;
        if(!is_null($wechat))$userInfo->wechat = $wechat;
        if(!is_null($weibo))$userInfo->weibo = $weibo;
        if(!is_null($maimai))$userInfo->maimai = $maimai;
        if(!is_null($edu_school))$userInfo->edu_school = $edu_school;
        if(!is_null($position))$userInfo->position = $position;
        if(!is_null($user_desc))$userInfo->user_desc = $user_desc;

        $userInfo->save();

        if($role==1) return $id;
        return $this->buildResponse(trans('api.user.edit_user_info.success'),$userInfo);

    }

    /**
     * 删除创业者信息
     * @param Guard $guard
     * @param $id
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     * @throws \Exception
     */
    public function delUserInfoByAdmin(Guard $guard  ,  $id=0)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        if($id) {
            $res1 = User::find($id)->delete();
        }
        if($res1)
            return $this->buildResponse(trans('api.user.delete_user_info.success'));
        else
            throw new AdminException(AdminException::DeleteHandleIsFail);

    }

    /**
     * 编辑投资人信息
     * @param Guard $guard
     * @param ChangeUserInfoRequest $request
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function editInvestorByAdmin(Guard $guard , ChangeUserInfoRequest $request)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        if(!User::isAdmins($guard->user()->id))
            throw new SecurityException(SecurityException::NoPermission);

        $tmpId      =   $this->editUserInfoByAdmin($guard , $request , 1 );

        $userId     =   $tmpId ;
        $orgId      =   !is_null($request->get('org_id')) ? $request->get('org_id'):0;

        if($userId == 0 ){
            $investor  = new Investor();
        }else{
            if(Investor::whereUserId($tmpId)->exists())
                $investor  = Investor::whereUserId($tmpId)->first();
            else
                $investor  = new Investor();
        }

        $investor->user_id = $tmpId;
        $investor->org_id  = $orgId;
        if(!is_null($request->get('invest_num_small'))) $investor->invest_num_small = $request->get('invest_num_small');
        if(!is_null($request->get('invest_num_big'))) $investor->invest_num_big = $request->get('invest_num_big');
        $investor->save();

        $fields = $request->get('fields');
        $phases = $request->get('phases');

        if(!is_null($fields)){
            $fields = array_diff($fields , $investor->investor_x_fields()->lists('field_id'));
            if($fields)
                $investor-> investor_x_fields()->attach($fields);
        }

        if(!is_null($phases)){
            $phases = array_diff($phases , $investor->investor_x_phases()->lists('phase_id'));
            if($phases)
                $investor->investor_x_phases()->attach($phases);
        }
       return redirect(route('Admin.Users.getInvestorList'));

    }

    /**
     * 通过投资机构名字获取投资机构标识
     * @return int|mixed
     */
    public function searchInvestOrgByOrgName()
    {
        $orgId = 0;
        $name  = Input::get('invest_name');
        if(!empty($name)){
            if(InvestOrg::whereInvestName($name)->exists())
                $org = InvestOrg::whereInvestName($name)->first();

        }
        if(isset($org->id))
            return $this->buildResponse(trans('api.admin.search.investOrg.success') , $org->id);
        else
            return $this->buildResponse(trans('api.admin.search.investOrg.fail') ,[] , null ,'error');

    }



    /**
     * 通过项目标识 审核项目
     * @param Guard $guard
     * @param int $auth
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function checkProjectByIdByAdmin(Guard $guard , $auth=-2 )
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $id = Input::get('id');
        /** 项目已经审核通过 */
        if(Project::whereId($id)->whereProjectAuth(1)->exists())
            return $this->buildResponse(trans('This project has been approved.') ,[] , null ,'error');

        if($id != 0)
            $project = Project::find($id);
        else
            return $this->buildResponse(trans('api.admin.check.project.fail') ,[] , null ,'error');

        $project->project_auth  = $auth;
        $project->save();
        return $this->buildResponse(trans('api.admin.check.project.success'));

    }


    /**
     * 通过投资人标识 审核投资人
     * @param Guard $guard
     * @param int $auth
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function checkInvestorByIdByAdmin(Guard $guard , $auth=-2)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $id = Input::get('id');
        if(Investor::whereId($id)->whereStatus(1)->exists())
            return $this->buildResponse(trans('This investor has been approved.') ,[] , null ,'error');

        if($id != 0)
            $investor = Investor::find($id);
        else
            return $this->buildResponse(trans('api.admin.check.investor.fail') ,[] , null ,'error');

        $investor->status = $auth ;
        $investor->save();

        return $this->buildResponse(trans('api.admin.check.investor.success'));

    }

    /**
     * 通过投资机构标识 审核投资机构
     * @param Guard $guard
     * @param int $auth
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function checkInvestOrgByIdByAdmin(Guard $guard , $auth=-2 )
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $id = Input::get('id');
        if(InvestOrg::whereId($id)->whereStatus(1)->exists())
            return $this->buildResponse(trans('This Invest-org has been approved.') ,[] , null ,'error');

        if($id != 0)
            $org = InvestOrg::find($id);
        else
            return $this->buildResponse(trans('api.admin.check.invest-org.fail') ,[] , null ,'error');

        $org->status    = $auth ;
        $org->save();

        return $this->buildResponse(trans('api.admin.check.investor-org.success'));

    }

    /**
     * 通过里程碑标识 删除里程碑
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function DeleteMilestoneById(Guard $guard)
    {
        $id = Input::get('id');
        if(!ProjectMilestone::whereId($id)->exists())
            return $this->buildResponse(trans('This Milestone is null.') ,[] , null ,'error');

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        if($id !=0 && ProjectMilestone::whereId($id)->exists()){
            $milestone  = ProjectMilestone::find($id)->delete();
            if($milestone)
                return $this->buildResponse(trans('api.milestone.deleted.success'));
        }

    }

    /**
     * 通过项目标识 或行业标识 删除行业
     * @param Guard $guard
     * @param ProjectRequest $request
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     */
    public function delProjectField(Guard $guard , ProjectRequest $request)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $proId = !is_null($request->get('pro_id')) ? $request->get('pro_id') : 0 ;
        $fieldId = !is_null($request->get('field_id')) ? $request->get('field_id') : 0 ;

        if(!$proId || !$fieldId)
            throw new AdminException(AdminException::NoProjectIdOrFieldId);

        $project = Project::find($proId);
        $project->project_x_fields()->detach($fieldId);

        return $this->buildResponse(trans('api.project-field.deleted.success'));
    }

    /**
     * 通过项目标识和图片标识删除 项目总览图片
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     */
    public function delOverviewImageById(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $proId = Input::get('pro_id');
        $imgId = Input::get('img_id');

        if(!$proId || !$imgId)
            throw new AdminException(AdminException::NoProjectIdOrImageId);

        $project = Project::find($proId);
        $project->project_x_overview_img()->detach($imgId);

        return $this->buildResponse(trans('api.project-overview-image.deleted.success'));
    }

    /**
     * 通过项目标识 和 团队标识 删除 团队信息
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     */
    public function delTeamByProIdAndTeamId(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $proId      = Input::get('proId');
        $teamId     = Input::get('teamId');

        if(!$proId || !$teamId)
            throw new AdminException(AdminException::NoProjectIdOrTeamId);
        $project = Project::find($proId);
        $project->project_x_team()->detach($teamId);

        return $this->buildResponse(trans('api.project-team.deleted.success'));
    }

    /**
     * 获取要编辑的团队信息
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     */
    public function getTeamByTeamId(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $teamId     = Input::get('teamId');
        $team       = UserTeams::find($teamId);

        if($team)
            return $this->buildResponse(trans('api.project-team.deleted.success') ,$team);
        else
            throw new AdminException(AdminException::NoData);
    }


    /**
     * 通过项目标识 获取该项目的所以成员信息
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     */
    public function getTeamByProId(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $proId      = Input::get('proId');
        $project    = Project::find($proId);
        $teams      = $project->project_x_team;

        if($teams)
            return $this->buildResponse(trans('api.project-team.deleted.success') ,$teams);
        else
            throw new AdminException(AdminException::NoData);

    }


    /***
     * 通过项目标识获取里程碑信息
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     */
    public function getMilestoneByProId(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $proId      = Input::get('proId');
        $milestones = ProjectMilestone::whereProjectId($proId)->get();

        if($milestones)
            return $this->buildResponse(trans('api.project-team.deleted.success') ,$milestones);
        else
            throw new AdminException(AdminException::NoData);
    }

    /**
     * 通过管理员标识  编辑 管理员基本信息
     * @param Guard $guard
     * @param int $id
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SignUpException
     */
    public function editAdminById(Guard $guard , $id=0)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $username   =   Input::get('username');
        $email      =   Input::get('email');
        $phone      =   Input::get('phone');
        $password   =   Input::get('password');

        if($id == 0)
            $user       = new User();
        else
            $user       = User::find($id);

        $user->username = !is_null($username) ? $username:null;
        $user->email    = Tools::isEmail($email) ? $email:null;
        $user->phone    = Tools::isPhone($phone) ? $phone:null;
        $user->password = !empty($password) ? bcrypt($password) : $user->password;
        $user->reg_ip   = \Input::ip();
        $user->reg_time = Carbon ::now();
        $user->login_ip = '';
        $user->login_time   = date('Y-m-d',time());
        $user->login_count  = 0;
        $user->is_power     = 3;
        $user->save();

        return $this->buildResponse(trans('api.project-team.deleted.success') ,$user);

    }

    /**
     * 通过管理员标识 获取管理员信息
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     */
    public function GetAdminById(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $userId     = Input::get('userId');
        $admin      = User::find($userId);

        if($admin)
            return $this->buildResponse(trans('api.get-admin.success') ,$admin);
        else
            throw new AdminException(AdminException::NoData);

    }

    /**
     * 通过用户标识 删除 admin用户
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     * @throws \Exception
     */
    public function delAdminById(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $userId     = Input::get('userId');
        $res        = User::find($userId)->delete();
        if($res)
            return $this->buildResponse(trans('api.admin.deleted.success'));
        else
            throw new AdminException(AdminException::DeleteHandleIsFail);


    }

    /**
     * 通过投资机构标识 删除 投资机构
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     * @throws \Exception
     */
    public function delInvestOrgById(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $orgId  = Input::get('orgId');
        $res    = InvestOrg::find($orgId)->delete();
        if($res)
            return $this->buildResponse(trans('api.invest.org.deleted.success'));
        else
            throw new AdminException(AdminException::DeleteHandleIsFail);
    }

    /**
     * 通过项目标识 删除项目
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     * @throws \Exception
     */
    public function DeleteProjectById(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $proId  = Input::get('proId');
        $res    = Project::find($proId)->delete();
        if($res)
            return $this->buildResponse(trans('api.project.deleted.success'));
        else
            throw new AdminException(AdminException::DeleteHandleIsFail);

    }

    /**
     * 删除投资阶段
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     */
    public function delInvestorPhase(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $userId     = Input::get('user_id') ;
        $phaseId    = Input::get('phase_id') ;

        if(!$userId || !$phaseId)
            throw new AdminException(AdminException::NoInvestorIdOrPhaseId);

        $investor = Investor::whereUserId($userId)->first();
        $investor->investor_x_phases()->detach($phaseId);

        return $this->buildResponse(trans('api.investor-phase.deleted.success'));
    }

    /**
     * 删除投资领域
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws AdminException
     * @throws SecurityException
     */
    public function delInvestorField(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        if(!User::isAdmins($userId))
            throw new SecurityException(SecurityException::NoPermission);

        $userId = Input::get('user_id') ;
        $fieldId = Input::get('field_id') ;

        if(!$userId || !$fieldId)
            throw new AdminException(AdminException::NoInvestorIdOrFieldId);

        $investor = Investor::whereUserId($userId)->first();
        $investor->investor_x_fields()->detach($fieldId);

        return $this->buildResponse(trans('api.investor-field.deleted.success'));
    }


}